package com.liustar.jpush;

import cn.jiguang.common.ClientConfig;
import cn.jiguang.common.DeviceType;
import cn.jiguang.common.connection.HttpProxy;
import cn.jpush.api.JPushClient;
import cn.jpush.api.push.model.*;
import cn.jpush.api.push.model.audience.Audience;
import cn.jpush.api.push.model.audience.AudienceTarget;
import cn.jpush.api.push.model.audience.AudienceType;
import cn.jpush.api.push.model.notification.AndroidNotification;
import cn.jpush.api.push.model.notification.IosAlert;
import cn.jpush.api.push.model.notification.IosNotification;
import cn.jpush.api.push.model.notification.Notification;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by Leo on 2017/7/19.
 */
public class PushUtils extends JPushClient {
    private static final Logger logger = LoggerFactory.getLogger(PushUtils.class);

    public PushUtils(String masterSecret, String appKey) {
        super(masterSecret, appKey);
    }

    public PushUtils(String masterSecret, String appKey, HttpProxy proxy, ClientConfig conf) {
        super(masterSecret, appKey, proxy, conf);
    }

    public final static String PLATFORM_ALL = "all";
    public final static String PLATFORM_ANDROID = "android";
    public final static String PLATFORM_IOS = "ios";
    public final static String PLATFORM_ANDROID_IOS = "android_ios";

    public final static String AUDIENCE_ALL = "all";
    /**
     * 不推送
     */

    public final static String TYPE_NOPUSH = "NOTPUSH";
    /**
     * 消息
     */
    public final static String TYPE_MESSAGE = "MESSAGE";
    /**
     * 通知
     */
    public final static String TYPE_NOTIFICATION = "NOTIFICATION";
    /**
     * 消息和通知
     */
    public final static String TYPE_MESSAGE_NOTIFICATION = "MESSAGE_NOTIFICATION";

    /**
     * 构建推送对象
     *
     * @param pushData
     * @return
     */
    public PushPayload buildPayload(PushData pushData) {
        PushPayload payload = null;
        try {
            PushPayload.Builder payloadBuilder = PushPayload.newBuilder();

            //推送平台
            Platform.Builder platformBuilder = Platform.newBuilder();
            if (pushData.getPlatform().equals(PLATFORM_ALL)) {
                platformBuilder.setAll(true);
            } else if (pushData.getPlatform().equals(PLATFORM_ANDROID)) {
                platformBuilder.addDeviceType(DeviceType.Android);
            } else if (pushData.getPlatform().equals(PLATFORM_IOS)) {
                platformBuilder.addDeviceType(DeviceType.IOS);
            } else if (pushData.getPlatform().equals(PLATFORM_ANDROID_IOS)) {
                platformBuilder.addDeviceType(DeviceType.Android);
                platformBuilder.addDeviceType(DeviceType.IOS);
            }
            payloadBuilder.setPlatform(platformBuilder.build());

            Options.Builder optionsBuilder = Options.newBuilder();
            if (pushData.getTimeToLive().longValue() > 0) {
                optionsBuilder.setTimeToLive(pushData.getTimeToLive().longValue());
                payloadBuilder.setOptions(optionsBuilder.build());
            }

            if (!isEmpty(pushData.getMessage())) {
                //消息
                Message.Builder messageBuilder = Message.newBuilder();
                messageBuilder.setContentType(pushData.getContentType())
                        .setMsgContent(pushData.getMessage())
                        .setTitle(pushData.getTitle())
                        .addExtras(pushData.getBizData());
                payloadBuilder.setMessage(messageBuilder.build());
            }
            if (!isEmpty(pushData.getNotification())) {
                //通知
                Notification.Builder notificationBuilder = Notification.newBuilder();

                AndroidNotification.Builder androidNotificationBuilder = AndroidNotification.newBuilder();
                androidNotificationBuilder.setTitle(pushData.getTitle())
                        .setAlert(pushData.getNotification())
                        .addExtras(pushData.getBizData());

                IosAlert iosAlert = IosAlert.newBuilder().
                        setTitleAndBody(pushData.getTitle(), "", pushData.getNotification())
                        .build();
                IosNotification.Builder iosNotificationBuilder = IosNotification.newBuilder();
                iosNotificationBuilder.incrBadge(1).setAlert(iosAlert)
                        .setSound("default")
                        .setMutableContent(true)
                        .setContentAvailable(true)
                        .addExtras(pushData.getBizData());

                notificationBuilder.addPlatformNotification(androidNotificationBuilder.build())
                        .addPlatformNotification(iosNotificationBuilder.build());

                payloadBuilder.setNotification(notificationBuilder.build());
            }
            if (!isEmpty(pushData.getSmsMessage())) {
                SMS.Builder smsBuilder = SMS.newBuilder();
                smsBuilder.setContent(pushData.getSmsMessage());
                smsBuilder.setDelayTime(pushData.getDelayTime());
                payloadBuilder.setSMS(smsBuilder.build());
            }

            //发送对象

            Audience.Builder audienceBuilder = Audience.newBuilder();
            if ("all".equalsIgnoreCase(pushData.getRegid())) {
                audienceBuilder.setAll(true);
            } else {
                //发送对象:REGISTRATION_ID
                AudienceTarget.Builder audienceTargetBuilder = AudienceTarget.newBuilder();
                audienceTargetBuilder.setAudienceType(AudienceType.REGISTRATION_ID);
                if (null != pushData.getRegIds() && pushData.getRegIds().size() > 0) {
                    audienceTargetBuilder.addAudienceTargetValues(pushData.getRegIds());
                    audienceBuilder.addAudienceTarget(audienceTargetBuilder.build());
                } else if (!isEmpty(pushData.getRegid())) {
                    List<String> regIds = new ArrayList<>();
                    regIds.add(pushData.getRegid());
                    audienceTargetBuilder.addAudienceTargetValues(regIds);
                    audienceBuilder.addAudienceTarget(audienceTargetBuilder.build());
                }
                //发送对象:别名
                audienceTargetBuilder = AudienceTarget.newBuilder();
                audienceTargetBuilder.setAudienceType(AudienceType.ALIAS);
                if (null != pushData.getAliases() && pushData.getAliases().size() > 0) {
                    audienceTargetBuilder.addAudienceTargetValues(pushData.getAliases());
                    audienceBuilder.addAudienceTarget(audienceTargetBuilder.build());
                } else if (!isEmpty(pushData.getAlias())) {
                    List<String> aliases = new ArrayList<>();
                    aliases.add(pushData.getAlias());
                    audienceTargetBuilder.addAudienceTargetValues(aliases);
                    audienceBuilder.addAudienceTarget(audienceTargetBuilder.build());
                }
                //发送对象:标签
                audienceTargetBuilder = AudienceTarget.newBuilder();
                audienceTargetBuilder.setAudienceType(AudienceType.TAG);
                if (null != pushData.getTags() && pushData.getTags().size() > 0) {
                    audienceTargetBuilder.addAudienceTargetValues(pushData.getTags());
                    audienceBuilder.addAudienceTarget(audienceTargetBuilder.build());
                } else if (!isEmpty(pushData.getTag())) {
                    List<String> tags = new ArrayList<>();
                    tags.add(pushData.getTag());
                    audienceTargetBuilder.addAudienceTargetValues(tags);
                    audienceBuilder.addAudienceTarget(audienceTargetBuilder.build());
                }
                //发送对象:标签与
                audienceTargetBuilder = AudienceTarget.newBuilder();
                audienceTargetBuilder.setAudienceType(AudienceType.TAG_AND);
                if (null != pushData.getTagAnds() && pushData.getTagAnds().size() > 0) {
                    audienceTargetBuilder.addAudienceTargetValues(pushData.getTagAnds());
                    audienceBuilder.addAudienceTarget(audienceTargetBuilder.build());
                } else if (!isEmpty(pushData.getTagAnd())) {
                    List<String> tagAnds = new ArrayList<>();
                    tagAnds.add(pushData.getTagAnd());
                    audienceTargetBuilder.addAudienceTargetValues(tagAnds);
                    audienceBuilder.addAudienceTarget(audienceTargetBuilder.build());
                }
                //发送对象:标签非
                audienceTargetBuilder = AudienceTarget.newBuilder();
                audienceTargetBuilder.setAudienceType(AudienceType.TAG_NOT);
                if (null != pushData.getTagNots() && pushData.getTagNots().size() > 0) {
                    audienceTargetBuilder.addAudienceTargetValues(pushData.getTagNots());
                    audienceBuilder.addAudienceTarget(audienceTargetBuilder.build());
                } else if (!isEmpty(pushData.getTagNot())) {
                    List<String> tagNots = new ArrayList<>();
                    tagNots.add(pushData.getTagNot());
                    audienceTargetBuilder.addAudienceTargetValues(tagNots);
                    audienceBuilder.addAudienceTarget(audienceTargetBuilder.build());
                }
                //发送对象:对象组
                audienceTargetBuilder = AudienceTarget.newBuilder();
                if (!isEmpty(pushData.getSegment())) {
                    audienceTargetBuilder.setAudienceType(AudienceType.SEGMENT);
                    audienceTargetBuilder.addAudienceTargetValues(pushData.getSegment());
                    audienceBuilder.addAudienceTarget(audienceTargetBuilder.build());
                }
            }
            payloadBuilder.setAudience(audienceBuilder.build());

            payload = payloadBuilder.build();
        } catch (Exception e) {
            logger.error("build payload error,error:{}", e.getMessage());
        }
        return payload;
    }

    private boolean isEmpty(String str) {
        return str == null || str.length() == 0;
    }

}
